$(function() {
    $('#post-comment').hide();
    $('#btn-comment').on('click', function(event) {
        event.preventDefault();
        $('#post-comment').slideDown();
    });
    $('#comment-btn').on('click', function(event) {
        $('#post-comment').hide();
    });
    $('#btn-like').on('click', function() {
        var self = this;
        fetch('/images/like', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({imageid: $(self).data('id')})
        })
        .then(function(response) {
            return response.json();
        })
        .then(function(obj) {
            $('strong.like-count').text(obj.likes)
            var likes = $('.SumLikes').html();
            $('.SumLikes').text(Number(likes)+1);
        })
        .catch(function(err) {
            alert('出错了，无法点赞。')
        })
    })

    $('#btn-delete').on('click', function(event) {
        event.preventDefault();
        var $this = $(this);
        var remove = confirm('Are you sure delete this image?');
        if (remove) {
            var imgId = $(this).data('id');
            $.ajax({
                url: '/images/' + imgId,
                type: 'DELETE'
            }).done(function(result) {
                if (result.res) {
                    //$('#btn-like').hide();
                    $this.removeClass('btn-danger').addClass('btn-success');
                    $this.find('i').removeClass('fa-times').addClass('fa-check');
                    $this.append('<span> Deleted!</span>');
                    $('#btn-delete').attr("disabled",true);
                    setTimeout("window.location.href='http://127.0.0.1:3000/'",1000);
                }
            });
        }
    });

    $('#comment-delete').on('click', function(event) {
        event.preventDefault();
        var $this = $(this);
        var path = $(this).data('id');
        var remove = confirm('Are you sure delete this comment?');
        if (remove) {
            var path = $(this).data('id');
            $.ajax({
                url: '/images/' + path,
                type: 'DELETE'
            }).done(function(result) {
                if (result.res) {
                    //
                }
            });
        }
        setTimeout("window.location.reload();",100);
    });
    timeago().render(document.querySelectorAll('.need_to_be_rendered'),'zh_CN');
});
